package com.yaoz.cloud.restserver.rest;

import cn.hutool.json.JSONUtil;
import com.yaoz.cloud.restserver.entity.LoginUser;
import com.yaoz.cloud.restserver.entity.User;
import com.yaoz.cloud.restserver.mapper.UserMapper;
import com.yaoz.cloud.restserver.service.RedisService;
import com.yaoz.cloud.restserver.util.IpConfiguration;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class HelloRest {

    @Autowired
    private IpConfiguration ipConfiguration;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisService redisService;

    @Value("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.datasource.url}")
    private String dataUrl;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public Map<String, Object> hello(@RequestParam("name") String name) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", name);
        map.put("port", ipConfiguration.getPort());
        map.put("redisHost", redisHost);
        map.put("dataUrl", dataUrl);
        return map;
    }

    @RequestMapping(value = "/getTokenAndUserInfo", method = RequestMethod.GET)
    public Map<String, Object> getTokenAndUserInfo(@RequestParam("userCenterId") String userCenterId) {
        Object object = redisService.getStr("token." + userCenterId);
        if (object == null) {
            return null;
        }
        String jsonStr = object.toString().replace("\"", "");
        String userInfo = redisService.getStr(jsonStr).toString();
        String lastUser = StringEscapeUtils.unescapeJava(userInfo.substring(1, userInfo.length() - 1));
        LoginUser loginUser = JSONUtil.toBean(lastUser, LoginUser.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("token", jsonStr);
        map.put("userInfo", loginUser);
        return map;
    }

    @RequestMapping(value = "getAllUserInfo", method = RequestMethod.GET)
    public List<User> getAllUserInfo() {
        return userMapper.queryAllLoginUsers();
    }
}
